package com.gzbsoft.sc.common.config;
import io.ebean.EbeanServer;
import io.ebean.EbeanServerFactory;
import io.ebean.config.DocStoreConfig;
import io.ebean.config.ServerConfig;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
@Configuration
@ConfigurationProperties(prefix = "ebean.docstore")
@Data
public class EbeanConfig {
    private String url;
    private boolean generateMapping;
    private boolean dropCreate;
    private boolean create;
    private boolean active;
    private final DataSource dataSource;
    private final EbeanCurrentUserProvider currentUserProvider;

    public EbeanConfig(DataSource dataSource, EbeanCurrentUserProvider currentUserProvider) {
        this.dataSource = dataSource;
        this.currentUserProvider = currentUserProvider;
    }
    @Bean
    public EbeanServer createEbeanServer() {
        ServerConfig config = new ServerConfig();
        config.setName("db");
        config.setDataSource(dataSource);
        config.loadFromProperties();
        config.setDefaultServer(true);
        config.setCurrentUserProvider(currentUserProvider);
        DocStoreConfig docStoreConfig = new DocStoreConfig();
        docStoreConfig.setActive(active);
        docStoreConfig.setCreate(create);
        docStoreConfig.setDropCreate(dropCreate);
        docStoreConfig.setGenerateMapping(generateMapping);
        docStoreConfig.setUrl(url);
        config.setDocStoreConfig(docStoreConfig);
        return EbeanServerFactory.create(config);
    }
}
